using System;
using System.Net.Http;
using System.Net.Http.Formatting;
using Newtonsoft.Json.Serialization;
using Sustainalytics.ESGRatings.Computing.Entities;
using Sustainalytics.ESGRatings.Computing.Entities.ESG;


namespace Sustainalytics.ESGComputing.Service.Tests
{
    public class ComputingFixture : Disposable
    {
        private const string SutLink = "http://localhost:10280/esgcomputingserv/api/v1";

        private static readonly JsonMediaTypeFormatter JsonMediaTypeFormatter = new JsonMediaTypeFormatter
        {
            SerializerSettings = { ContractResolver = new CamelCasePropertyNamesContractResolver() }
        };

        private static HttpClient _sutClient = new HttpClient();
        private readonly CompanyData[] _companies;
        private bool _disposed;
        private readonly Guid _matrixId;
        private readonly Guid _universeId;
        private readonly CompanyScores[] scores;
        public WeightMatrix[] Matrices { get; private set; }


        public ComputingFixture()
        {
            var dataBuilder = new TenCompaniesTwoGroupsOneUniverseFakes();
            var data = dataBuilder.PrepareData();
            _universeId = dataBuilder.ReferenceUniversesId;
            scores = data.CompaniesScores;
            Matrices = data.Matrices;
            _matrixId = dataBuilder.MatrixId;
            _companies = data.Companies;
            var taskAsync = _sutClient.PostAsync(string.Format("{0}{1}", SutLink, "/dataprovisioning/esgsets"), data, JsonMediaTypeFormatter);
            var result = taskAsync.Result;
            result.EnsureSuccessStatusCode();
        }

        ~ComputingFixture()
        {
            Dispose(false);
        }

        public CompanyData[] Companies
        {
            get { return _companies; }
        }

        public CompanyScores[] Scores
        {
            get { return scores; }
        }

        public Guid MatrixId
        {
            get { return _matrixId; }
        }

        public Guid UniverseId
        {
            get { return _universeId; }
        }

        protected override void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    var taskClean = _sutClient.PostAsync(string.Format("{0}{1}", SutLink, "/health/clean"), string.Empty,
                        JsonMediaTypeFormatter);
                    taskClean.Result.EnsureSuccessStatusCode();
                    _sutClient.Dispose();
                    _sutClient = null;
                }
                _disposed = true;
            }
            base.Dispose(disposing);
        }
    }
}